package com.hangzhou.welbeing.welbeinginstrument.fragement;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.activity.AllCircleActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.ReleaseSimilarProfilePageFocusedActivity;
import com.hangzhou.welbeing.welbeinginstrument.activity.ReleaseTrueCicleActivity;
import com.hangzhou.welbeing.welbeinginstrument.adapter.PopularCircleAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.RecommendedAdapter;
import com.hangzhou.welbeing.welbeinginstrument.adapter.ReleaseFindAdapter;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.AttentionPostBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.CancelAttentionPostBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.EventZanBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.GuessYouLikeDateBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.HotsCircleDataBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.MyPoUrl;
import com.hangzhou.welbeing.welbeinginstrument.bean.PraiseBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.deleteOthersBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemClickListener;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemZanListener;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司18
 * Created by 20433 on 2018/1/31
 */

public class releaseFindFragment extends Fragment {
    @Bind(R.id.fragment_release_find_XRecyclerView)
    XRecyclerView fragmentReleaseFindXRecyclerView;

    private boolean flag = true;
    private int p = 1;
    private RecommendedAdapter recommendedAdapter;
    private RelativeLayout rl_all_circle;
    private RecyclerView header_01_recyclerView;
    private PopularCircleAdapter popularCircleAdapter;
    private  List<HotsCircleDataBean.DataBean> mlistbean = new ArrayList<>();
    private List<GuessYouLikeDateBean.DataBean> databean = new ArrayList<>();
    private Context mcontext;
    private ReleaseFindAdapter releaseFindAdapter;
    private int thumbUpNumber;
    private PopupWindow popupWindow;
    private int lstatedate;
    private int hits_like_01;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mcontext = context;
        EventBus.getDefault().register(this);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(mcontext, R.layout.fragment_release_find, null);
        ButterKnife.bind(this, view);
        showProgress("加载中...");
        LinearLayoutManager layoutManager = new LinearLayoutManager(mcontext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentReleaseFindXRecyclerView.setLayoutManager(layoutManager);
        fragmentReleaseFindXRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        fragmentReleaseFindXRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        fragmentReleaseFindXRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);
        View header = LayoutInflater.from(mcontext).inflate(R.layout.fragment_find_header_01, container,false);
        findHeaderView(header);
        fragmentReleaseFindXRecyclerView.addHeaderView(header);
        fragmentReleaseFindXRecyclerView.setPullRefreshEnabled(false);  //TODO 禁止下拉刷新完毕
        fragmentReleaseFindXRecyclerView.getDefaultFootView().setNoMoreHint("就这么多了");
        fragmentReleaseFindXRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                flag = true;
                loadDate(p);
            }

            @Override
            public void onLoadMore() {
                p++;
                flag = false;
                loadDate(p);

            }
        });
        releaseFindAdapter = new ReleaseFindAdapter(mcontext,databean);
        fragmentReleaseFindXRecyclerView.setAdapter(releaseFindAdapter);
        fragmentReleaseFindXRecyclerView.refresh();
        releaseFindAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view) {
                int postion = fragmentReleaseFindXRecyclerView.getChildAdapterPosition(view) -2;
                GuessYouLikeDateBean.DataBean datalist = databean.get(postion);

                if(datalist != null ){
                    List<MyPoUrl>  mlist = new ArrayList<MyPoUrl>();
                    for (String s : datalist.po_url) {
                        mlist.add(new MyPoUrl(s));
                    }
                   // Log.e("tag","+++++lstatedate+++=====******+  "+lstatedate);
                    Intent intent = new Intent(mcontext, ReleaseSimilarProfilePageFocusedActivity.class);
                    intent.putExtra("posts_deleted", "releaseFindFragment");
                    intent.putExtra("posts_deleted_id", postion);
                    //Log.e(TAG,"praiseParseNetworkResponse===555=========>"+ datalist.lstate);
                    intent.putExtra("po_id", datalist.po_id);
                    intent.putExtra("po_name", datalist.po_name);
                    intent.putExtra("addtime", datalist.addtime);
                    intent.putExtra("video", datalist.video);
                    intent.putExtra("vpic", datalist.vpic);
                    intent.putExtra("content", datalist.content);
                    intent.putExtra("cat_id", datalist.cat_id);
                    intent.putExtra("cus_id", datalist.cus_id);
                    intent.putExtra("cus_name", datalist.cus_name);
                    intent.putExtra("cus_logo", datalist.cus_logo);
                    intent.putExtra("hits_like", datalist.hits_like);
                    intent.putExtra("lstate", datalist.lstate);
                    intent.putExtra("col", datalist.col);
                    intent.putExtra("state", datalist.state);
                    intent.putExtra("count", datalist.count);
                    intent.putExtra("lCount", datalist.lCount);
                    intent.putExtra("po_url", (Serializable) datalist.po_url);
                    startActivity(intent);
                }
            }
            @Override
            public void onItemFirstButtonClick(View v, int position) {
               // Log.e("tag","parseNetworkResponse===releaseFindFragment=postion===="+position);
                TextView textView= (TextView) v;
                String str = textView.getText().toString().trim();
                String attention_id = databean.get(position).cus_id;
                if(str.equals("关注")){  //todo 调用关注的方法
                    addAttentionPost(textView,attention_id);
                }else if(str.equals("已关注")){  //todo 调用取消关注的方法
                    cancelAttentionPost(textView,attention_id);
                }
            }
        });
        releaseFindAdapter.setmOnItemZanClickListener(new OnRecyclerViewItemZanListener() {


            @Override
            public void onItemZanClick(View v, int position, View view) {

                ImageView imageView= (ImageView) v;
                TextView textView= (TextView) view;
                String cat_id_01 =  databean.get(position).cat_id;
                String po_id_01 =  databean.get(position).po_id;
                String thumbUp = textView.getText().toString().trim();
                try {
                    thumbUpNumber = Integer.parseInt(thumbUp);
                    giveLike(cat_id_01,imageView,po_id_01,textView,position);
                } catch (NumberFormatException e) {
                }

            }
        });
        loadDate(p);
        return view;
    }



    /**
     * @desc 加载帖子数据
     * */
    private void loadDate(int p) {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.RECOMMEND_POST)
                .addParams("cus_id", user_id)
                .addParams("p", p+"")
                .addParams("pp", "8")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse = response.body().string();
                        Gson gson =  new Gson();
                       // Log.e("tag","+++++loadDate+++=====******+  "+parseNetworkResponse);
                        final GuessYouLikeDateBean   guessYouLikeDateBean = gson.fromJson(parseNetworkResponse, GuessYouLikeDateBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(guessYouLikeDateBean.errorCode == 200){
                                    popupWindow.dismiss();
                                    // TODO 处理数据
                                    List<GuessYouLikeDateBean.DataBean> mdatabean = guessYouLikeDateBean.data;
                                    if(mdatabean != null && mdatabean.size() > 0){
                                        databean.addAll(mdatabean);
                                       // Log.e("tag","parseNetworkResponse==databean加载帖子数据====="+databean.size());
                                        if(flag){
                                            if(fragmentReleaseFindXRecyclerView != null){
                                                fragmentReleaseFindXRecyclerView.refreshComplete(); //TODO 下拉刷新完毕
                                            }

                                        }else{
                                            if(fragmentReleaseFindXRecyclerView != null){
                                                fragmentReleaseFindXRecyclerView.loadMoreComplete();  //TODO 上拉加载完毕
                                            }
                                        }
                                    }else{
                                        if(fragmentReleaseFindXRecyclerView != null){
                                            fragmentReleaseFindXRecyclerView.setNoMore(true);
                                        }
                                    }
                                    releaseFindAdapter.notifyDataSetChanged();
                                }else{
                                    popupWindow.dismiss();
                                    Toast.makeText(mcontext,guessYouLikeDateBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        popupWindow.dismiss();
                        Toast.makeText(mcontext,"未加载到帖子数据",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc 查找控件
     * */
    private void findHeaderView(View header) {
        rl_all_circle = (RelativeLayout) header.findViewById(R.id.fragment_find_header_01_rl_all_circle);
        header_01_recyclerView = (RecyclerView) header.findViewById(R.id.fragment_find_header_01_RecyclerView);
        rl_all_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(mcontext, AllCircleActivity.class);
                startActivity(intent);
            }
        });

        GridLayoutManager  layoutManager =   new GridLayoutManager(mcontext,3);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        header_01_recyclerView.setLayoutManager(layoutManager);
        popularCircleAdapter = new PopularCircleAdapter(mcontext);
        header_01_recyclerView.setAdapter(popularCircleAdapter);
        popularCircleAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view) { //TODO 跳转到圈子页面
                int postion  = header_01_recyclerView.getChildAdapterPosition(view);
                Intent intent = new Intent(mcontext, ReleaseTrueCicleActivity.class);
                intent.putExtra("circle_id", mlistbean.get(postion).id);
                intent.putExtra("circle_num", mlistbean.get(postion).num);
                intent.putExtra("circle_name",mlistbean.get(postion).cat_name);
                intent.putExtra("circle_state", mlistbean.get(postion).state + "");
                intent.putExtra("circle_url", mlistbean.get(postion).url);
                startActivity(intent);

            }

            @Override
            public void onItemFirstButtonClick(View v, int position) {

            }
        });
        loadPopularCircleDate();
    }



    /**
     * @desc 加载热门圈子的数据
     * */
    private void loadPopularCircleDate() {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id", "");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.HOSTS_CIRCLE)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String strresponse = response.body().string();
                        Gson gson = new Gson();
                       // Log.e("tag","+++++loadDate+++=========1234============++++"+strresponse);
                        final HotsCircleDataBean hotsCircleDataBean =  gson.fromJson(strresponse, HotsCircleDataBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(hotsCircleDataBean.errorCode == 200){
                                    popupWindow.dismiss();
                                    List<HotsCircleDataBean.DataBean> mdatebean =  hotsCircleDataBean.data;
                                    if(mdatebean != null && mdatebean.size() > 0){
                                        mlistbean.addAll(mdatebean);
                                        popularCircleAdapter.addItem(mdatebean);
                                        //Log.e("tag","+++++loadDate+++=========2435============++++");
                                    }
                                }else{
                                    popupWindow.dismiss();
                                    Toast.makeText(mcontext, hotsCircleDataBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        popupWindow.dismiss();
                        Toast.makeText(mcontext, "未加载到热门圈子的数据了", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     *
     * @desc 关注帖子
     * */
    private void addAttentionPost(final TextView textView, String attention_id) {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.ADD_ATTENTION_POST)
                .addParams("cus_id",user_id)
                .addParams("followed", attention_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String strresponse = response.body().string();
                        Gson gson = new Gson();
                        //Log.e("tag","+++++loadDate+++=========1234============++++"+strresponse);
                       final AttentionPostBean attentionPostBean =  gson.fromJson(strresponse,AttentionPostBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(attentionPostBean.errorCode == 200){
                                    textView.setText("已关注");
                                    Toast.makeText(mcontext, "关注成功", Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(mcontext, attentionPostBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mcontext, "关注失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }
    /**
     * @DESC 取消关注的方法
     * */
    private void cancelAttentionPost(final TextView textView, String attention_id) {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CANCLE_ATTENTION_POST)
                .addParams("cus_id", user_id)
                .addParams("followed", attention_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String strresponse = response.body().string();
                        Gson gson = new Gson();
                       // Log.e("tag","+++++loadDate+++=========1234============++++"+strresponse);
                        final CancelAttentionPostBean cancelAttentionPostBean =    gson.fromJson(strresponse, CancelAttentionPostBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(cancelAttentionPostBean.errorCode == 200){
                                    textView.setText("关注");
                                    Toast.makeText(mcontext, "取消关注", Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(mcontext, cancelAttentionPostBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mcontext, "取消关注失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc 点赞
     * @param cat_id_01
     * @param imageView
     * @param po_id_01
     * @param textView     */
    private void giveLike(String cat_id_01, final ImageView imageView, String po_id_01, final TextView textView, final int position) {
        SharedPreferences sp = mcontext.getSharedPreferences("second_app_internal_data", 0);
        String  user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.PRAISE)
                .addParams("cus_id", user_id)
                .addParams("cat_id", cat_id_01)
                .addParams("po_id", po_id_01)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        final String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                       // Log.e(TAG,"praiseParseNetworkResponse======555======>"+praiseParseNetworkResponse);
                        final PraiseBean praiseBean =  gson.fromJson(praiseParseNetworkResponse,PraiseBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(praiseBean.errorCode == 200){
                                    if(praiseBean.errorMessage.equals("点赞成功!")){
                                        if(thumbUpNumber >=0){
                                            lstatedate = 1;
                                            thumbUpNumber = thumbUpNumber +1;
                                            textView.setText(thumbUpNumber+"");
                                            // todo 通知消息详情页面 是否点赞和点赞数
                                            //EventBus.getDefault().postSticky(new GiveLikeEventBean(lstatedate,thumbUpNumber));
                                            GuessYouLikeDateBean.DataBean datalist = databean.get(position);
                                            datalist.lstate = lstatedate;
                                            datalist.hits_like = thumbUpNumber;
                                            databean.set(position,datalist);

                                        }
                                        imageView.setImageResource(R.mipmap.zanz_00);
                                        Toast.makeText(mcontext,"点赞成功",Toast.LENGTH_LONG).show();
                                    }else if(praiseBean.errorMessage.equals("点赞取消!")){
                                        if(thumbUpNumber >= 1){
                                            lstatedate = 0;
                                            thumbUpNumber = thumbUpNumber - 1;
                                            textView.setText(thumbUpNumber+"");
                                            // todo 通知消息详情页面 是否点赞和点赞数
                                           // EventBus.getDefault().postSticky(new GiveLikeEventBean(lstatedate,thumbUpNumber));
                                            GuessYouLikeDateBean.DataBean datalist = databean.get(position);
                                            datalist.lstate = lstatedate;
                                            datalist.hits_like = thumbUpNumber;
                                            databean.set(position,datalist);
                                        }

                                        imageView.setImageResource(R.mipmap.zan_90);
                                        Toast.makeText(mcontext,"取消点赞",Toast.LENGTH_LONG).show();
                                    }
                                }else{
                                    Toast.makeText(mcontext,praiseBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(mcontext,"点赞失败",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    /**
     * @desc 显示进度
     * */
    private void showProgress(String str) {
        popupWindow = new PopupWindow(mcontext);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = LayoutInflater.from(mcontext).inflate(R.layout.layout_show_progress_popupwindow_style,null);
        TextView tv_content = (TextView) view.findViewById(R.id.layout_show_progress_popupwindow_style_tv_content);
        tv_content.setText(str);
        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setAnimationStyle(R.style.anim_menu_bottombar);
        View rootview = View.inflate(mcontext,R.layout.activit_release_similar_profile_page_focused,null);
        popupWindow.showAtLocation(rootview,  Gravity.CENTER,0,0);

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    @Subscribe
    public void onEventMainThread(EventZanBean event){
       // Log.e(TAG,"praiseParseNetworkResponse=====进行相应的处理操作=555======>");
        //接收到发布者发布的事件后，进行相应的处理操作
        if(event.getIdentifier().equals("releaseFindFragment")){
           // Log.e(TAG,"praiseParseNetworkResponse=====进行相应的处理操作=releaseFindFragment======>");
            GuessYouLikeDateBean.DataBean datalist =   databean.get(event.getPostion());
            datalist.hits_like = event.getHits_like();
            datalist.lstate = event.getLstate1();
            databean.set(event.getPostion(),datalist);
            releaseFindAdapter.notifyDataSetChanged();
        }
    }
    @Subscribe
    public void onEventMainThread(deleteOthersBean event){
        //接收到发布者发布的事件后，进行相应的处理操作
        if(event.getDeleteString().equals("releaseFindFragment")){  //调用刷新 接口
            databean.clear();
            p = 1;
            loadDate(p);

        }
    }
}
